﻿using Abp.Application.Services;
using Abp.UI;
using Castle.Core.Internal;
using CheryABP.ApiAttribute;
using CheryABP.Common;
using CheryABP.Extensions;
using CheryABP.SystemSetitng;
using Microsoft.AspNetCore.Http;
using System;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace CheryABP.Interceptor
{
    public class InterceptMiddlware
    {
        private readonly RequestDelegate _next;
        protected system_login AdminInfo;

        public InterceptMiddlware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            if (PreProceed(context))
            {
                await _next(context);
            }
            else
            {
                context.Response.Redirect("/404.html");
            }
            //PostProceed(context);
        }
        /// <summary>
        /// 接口执行前进入
        /// </summary>
        /// <param name="context"></param>
        private bool PreProceed(HttpContext context)
        {
            try
            {
                var path = context.Request.Path;
                var _session = context.Session;
                if (path.HasValue && path.Value.Contains("/api/services/app/"))
                {
                    AdminInfo = AbpSessionExtension.GetObjectFromJson<system_login>(_session, DTKeys.SESSION_ADMIN_INFO);
                    if (AdminInfo == null)
                    {
                        //查找方法上的特性是否是忽略验证的特性
                        string funcName = path.Value.Substring(path.Value.LastIndexOf('/') + 1);
                        if (!funcName.Equals("GetLoginInfo"))
                        {
                            return false;
                        }
                    }
                    return true;
                }
                return true;
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }

        }
    }
}